using B.Z.BasicData.Infrastructure;
using B.Z.Inventory.API.Read.Application.Command;
using B.Z.Inventory.API.Read.DTO;
using B.Z.Inventory.Domain;
using B.Z.Inventory.ErrorCode;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.Z.Inventory.API.Read.Application.CommandHandler
{
    /// <summary>
    /// 库存金额占比查询命令处理器
    /// </summary>
    public class InventoryAmountRatioCommandHandler : IRequestHandler<InventoryAmountRatioCommand, APIResult<InventoryAmountRatioDto>>
    {
        private readonly IBaseRepository<T_Goods> goodsRepository;
        private readonly ILogger<InventoryAmountRatioCommandHandler> logger;

        public InventoryAmountRatioCommandHandler(IBaseRepository<T_Goods> goodsRepository, ILogger<InventoryAmountRatioCommandHandler> logger)
        {
            this.goodsRepository = goodsRepository;
            this.logger = logger;
        }

        public Task<APIResult<InventoryAmountRatioDto>> Handle(InventoryAmountRatioCommand request, CancellationToken cancellationToken)
        {
            APIResult<InventoryAmountRatioDto> result = new APIResult<InventoryAmountRatioDto>();
            result.Code = APIEnums.ok;

            try
            {
                // 获取所有未删除的货品数据
                var query = goodsRepository.GetAll()
                    .AsNoTracking()
                    .Where(x => !x.IsDelete);

                // 应用筛选条件
                if (request.StoreId.HasValue)
                {
                    // 这里可能需要根据实际的仓库货品关系表进行关联查询
                }

                // 计算总金额
                var totalAmount = query.Sum(x => (x.SystemNum ?? 0) * x.OnePrice);

                if (totalAmount == 0)
                {
                    result.Data = new InventoryAmountRatioDto
                    {
                        TotalCount = 0,
                        TotalAmount = 0,
                        GoodsAmountRatios = new List<GoodsAmountRatio>()
                    };
                    return Task.FromResult(result);
                }

                // 计算每个商品的金额占比
                var goodsAmountList = query
                    .Where(x => x.SystemNum > 0)
                    .Select(goods => new
                    {
                        GoodsId = goods.Id,
                        GoodsName = goods.GoodsName,
                        GoodsNumber = goods.GoodsNumber,
                        StockQuantity = goods.SystemNum ?? 0,
                        UnitPrice = goods.OnePrice,
                        TotalAmount = (goods.SystemNum ?? 0) * goods.OnePrice
                    })
                    .ToList()
                    .Select(goods => new GoodsAmountRatio
                    {
                        GoodsId = goods.GoodsId,
                        GoodsName = goods.GoodsName,
                        GoodsNumber = goods.GoodsNumber,
                        StockQuantity = goods.StockQuantity,
                        UnitPrice = goods.UnitPrice,
                        TotalAmount = goods.TotalAmount,
                        AmountPercentage = totalAmount > 0 ? Math.Round((double)goods.TotalAmount / (double)totalAmount * 100, 2) : 0
                    })
                    .OrderByDescending(x => x.AmountPercentage)
                    .Take(request.TopCount)
                    .ToList();

                result.Data = new InventoryAmountRatioDto
                {
                    TotalCount = goodsAmountList.Count,
                    TotalAmount = totalAmount,
                    GoodsAmountRatios = goodsAmountList
                };

                logger.LogInformation($"成功获取库存金额占比，共{goodsAmountList.Count}条记录，总金额：{totalAmount:C}");
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取库存金额占比时发生错误");
                result.Code = APIEnums.fail;
                result.Message = "获取库存金额占比失败";
            }

            return Task.FromResult(result);
        }
    }
}